package aspect;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect
@Component
public class OrderAspect {

    private final Random random = new Random();

    // 使用更精确的切入点表达式
    @Before("execution(* service.OrderService.*(..))")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    @After("execution(* service.OrderService.add(..)) || " +
            "execution(* service.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    @Around("execution(* service.OrderService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        System.out.println("方法 " + methodName + " 的返回值: " + result);
        System.out.println("方法 " + methodName + " 执行时间: " + (endTime - startTime) + "ms");

        return result;
    }

    @Before("execution(* service.OrderService.add(..)) || " +
            "execution(* service.OrderService.delete(..))")
    public void checkPermission() {
        int permission = random.nextInt(2);
        if (permission == 1) {
            System.out.println("权限检查: 没有权限执行此操作");
            throw new RuntimeException("权限不足，操作被终止");
        }
        System.out.println("权限检查: 有权限执行此操作");
    }
}